import {observable, action} from 'mobx';
import {WeaForm, WeaTableNew, WeaSwitch} from 'comsMobx';
import * as API from '../apis/hrmresourcetotal';
import * as Util from '../util/index';
import HrmBaseStore from './baseStore';
import {i18n} from "../public/i18n";
import {
    WeaLocaleProvider,
    WeaFormItem,
    WeaCheckbox
} from 'ecCom';
import {
    has,
    indexOf,
    findIndex,
    remove,
    isEmpty,
    dropRight,
    cloneDeep
} from 'lodash';

const getLabel = WeaLocaleProvider.getLabel;
const {
    TableStore
} = WeaTableNew;

export class HrmResourceTotal extends HrmBaseStore {
    title = () => getLabel('30804', "工作历程");
    @observable verified = false;
    @observable hasRight = false;
    @observable loading = false;
    @observable condition = [];
    @observable hrmId = ''
    @observable tableList = {}


    tabConfig = {
        tabs: [{
            color: '#000000',
            groupId: 'roleList',
            title: '',
            viewCondition: '1',
            searchType: ['base', 'advanced'],
            searchKey: '',
            doSearch: (params) => this.doSearch(params)
        }],
        tabChangeHandle: this.setActiveTab,
        keyParam: 'viewCondition',
        activeTabKey: '1'
    }
    otherListCondition = {};
    fields = [];
    authSearchCondition = {}
    fromid = '';
    selectedTableItem = {
        record: null,
        index: -1
    }
    dialogParams = { //override baseStore.dialogParams
        ...this.dialogPropsDef,
        style: {
            width: 820,
            height: 650
        },
        buttons: [],
        onCancel: () => {
            this.dialogParams.visible = false;
        },
        table: new TableStore(),
        treeData: [],
        cType: 'table'
    }

    initData = () => {
        this.containerInitFinished = {
            ...this.containerInitFinished,
            init: true
        }
        this.showTable = false;
        this.clearTableData();
        this.getFormInfo();
    }

    setTableColTitle = () => {
        this.tableConfig.columns.map(c => {
            if (typeof (c.title) == 'function')
                c.title = c.title();
        })
    }

    getFormInfo = () => {
        API.getFormInfo().then(data => {
            if (data.status === '1') {
                if (has(data, 'formField') && data.formField.length > 0) {
                    this.fields = data.formField[0].items;
                    this.setFormData('searchForm', data.formField);
                    this.refreshForm = new Date().getTime();
                }
            }
        }, error => {

        })
    }
    getSearchGroupItem = () => {
        let items = [];
        if (this.formTarget.searchForm != null && this.formTarget.searchForm.isFormInit) {
            const formParams = this.formTarget.searchForm.getFormParams();
            items.push({
                com: (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@8jgze9`}
                    labelCol={{span: 0}}
                    wrapperCol={{span: 24}}>
                    <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@tsfytv`} fieldConfig={this.fields[0]} form={this.formTarget.searchForm}
                               onChange={this.onChangeTransferType}/>
                </WeaFormItem>),
                col: 2
            })
            const browserFieldDomKey = `${formParams.transferType}id`;
            const index = findIndex(this.fields, {
                domkey: [browserFieldDomKey]
            })
            if (index >= 0) {
                let field = this.fields[index];
                items.push({
                    com: (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@22mogq`}
                        labelCol={{span: 0}}
                        wrapperCol={{span: 24}}>
                        <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@avillq`} fieldConfig={field} form={this.formTarget.searchForm}
                                   onChange={this.onBrowserChangeHandle}/>
                    </WeaFormItem>),
                    col: 2
                })
            }
        }
        return items;
    }

    @action
    getHasRight(params = {}) {
        API.getHasRight(params).then((data) => {
            this.loading = true;
            this.hasRight = data.hasRight;
            if (this.hasRight) {
                this.getHrmResourceTotal();
            }
            this.verified = true;
        });
    }

    getHrmResourceTotal(params = {}) {
        params.id = this.hrmId;
        API.getHrmResourceTotal(params).then((data) => {
            this.condition = data.conditions;
            this.loading = false;
        });
    }

    convertTreeData = (datas, pid = 0) => {
        let newDatas = [];
        datas && !isEmpty(datas) && datas.map((item, index) => {
            for (let key in datas[index]) {
                let v = datas[index][key];
                try {
                    newDatas.push({
                        childs: this.convertTreeData(v.submenus, String(v.categoryid)),
                        domid: String(v.categoryid),
                        haschild: v.hasChildren,
                        isopen: v.isOpen,
                        key: String(v.categoryid),
                        name: v.name,
                        pid: pid,
                        canClick: true,
                    })
                } catch (e) {
                }
            }
        })
        return newDatas;
    }
    onCheckBoxChange = (val, key) => {
        this.otherListCondition[key] = val;
        const formParams = this.formTarget.conditionForm.getFormParams();
        this.doSearch({...formParams});
    }
    @action onSelectHandle = (record, index) => {
        this.selectedTableItem = {
            record,
            index
        };
        delete this.formTarget.conditionForm;
        delete this.formTarget.conditionFormFields;
        const params = {
            fromid: this.hrmId,
            isFromTotal: 1,
            isHidden: true
        }
        if (record.codeName === 'Temail001') {
            Object.assign(params, {
                folderid: 0
            })
        } else if (record.codeName === 'Temail002') {
            Object.assign(params, {
                folderid: -1
            })
        }
        API.initModuleData(record.codeName, params).then(rs => {
            try {
                rs.map((result, index) => {
                    if (result.status === '1') {
                        switch (index) {
                            case 0:
                                if (this.tabConfig.tabs.length > 1)
                                    this.tabConfig.tabs = dropRight(this.tabConfig.tabs, this.tabConfig.tabs.length - 1);
                                this.tabConfig.tabs[0].groupId = '1';
                                this.tabConfig.tabs[0].title = '';
                                this.tabConfig.activeTabKey = '1';
                                this.tabConfig.tabSearchKey = '';
                                this.tabConfig.buttons = [];
                                this.setFormData('conditionForm', result.condition);
                                if (Array.isArray(result.condition) && result.condition[0].items != null) {
                                    this.tabConfig.tabs[0].searchType = ['base', 'advanced']
                                    this.tabConfig.tabs[0].searchKey = result.condition[0].items[0].domkey[0];
                                } else {
                                    this.tabConfig.tabs[0].searchType = ['base'];
                                    this.tabConfig.tabs[0].searchKey = 'categoryname'
                                }

                                    this.dialogParams = {
                                        ...this.dialogParams, ...this.dialogPropsDef,
                                        title: `${i18n.label.select()}${record.label}`
                                    }

                                if (has(result, 'tab')) {
                                    result.tab.map((tab, i) => {
                                        if (i === 0) {
                                            Object.assign(this.tabConfig.tabs[0], {
                                                title: tab.title,
                                                viewCondition: tab.key,
                                                groupId: tab.key
                                            })
                                        } else {
                                            const t = cloneDeep(this.tabConfig.tabs[0]);
                                            Object.assign(t, {
                                                title: tab.title,
                                                viewCondition: tab.key,
                                                groupId: tab.key
                                            })
                                            this.tabConfig.tabs.push(t);
                                        }
                                    })
                                    this.tabConfig.tabSearchKey = result.tabSearchKey;
                                }
                                if (has(result, 'tabBtns')) {
                                    let btns = [];
                                    result.tabBtns.map((def, i) => {
                                        btns.push(<WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@g0a70b@${i}`} {...def}
                                                               onChange={(val) => this.onCheckBoxChange(val, def.id)}/>);
                                    })
                                    this.tabConfig.buttons = btns;
                                }
                                break;
                            case 1:
                                if (has(result, 'sessionkey')) {
                                    const tableName = record.codeName;
                                    this.tableList[tableName] = new TableStore();
                                    this.tableList[tableName].getDatas(result.sessionkey, 1);
                                    this.dialogParams.table = this.tableList[tableName];
                                    this.dialogParams.cType = 'table';
                                } else {
                                    this.dialogParams.cType = 'tree';
                                    try {
                                        this.dialogParams.treeData = this.convertTreeData(JSON.parse(result.treeDataJson));
                                    } catch (e) {
                                        this.dialogParams.treeData = [];
                                    }
                                }
                                this.dialogParams.visible = true;
                                break;
                            default:
                                break;
                        }
                    }
                });
            } catch (e) {
            }
        }, error => {

        })
    }

    setTreeCheckedKeys = (ids) => {
        this.treeProps.checkedKeys = ids;
    }

    @action setActiveTab = (key) => {
        this.tabConfig.activeTabKey = key || this.tabConfig.tabs[0].viewCondition;
        const tabIndex = this.getTabIndex(this.tabConfig.tabs, key);
        if (tabIndex < 0) return;
        this.refreshDialog = new Date().getTime();
        const formParams = this.formTarget.conditionForm.getFormParams();
        this.doSearch({...formParams});
    }

    @action doSearch = (params) => {
        params = params || {};
        if (this.tabConfig.tabSearchKey != '')
            Object.assign(params, {[this.tabConfig.tabSearchKey]: this.tabConfig.activeTabKey});
        [...Object.keys(this.otherListCondition)].map(k => {
            Object.assign(params, {[k]: this.otherListCondition[k]});
        });
        API.getList(this.selectedTableItem.record.codeName, {
            ...params,
            fromid: this.hrmId,
            isFromTotal: 1,
            isHidden: true
        }).then(data => {
            if (data.status === '1') {
                // this.dialogParams.table.getDatas(data.sessionkey, 1);
                if (has(data, 'sessionkey')) {
                    this.dialogParams.table.getDatas(data.sessionkey, 1);
                } else {
                    try {
                        this.dialogParams.treeData = this.convertTreeData(JSON.parse(data.treeDataJson));
                    } catch (e) {
                        this.dialogParams.treeData = [];
                    }
                }
            }

        }, error => {

        })
    }

}